package com.loveto.service;

import java.net.URLEncoder;

import org.json.JSONObject;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.PowerManager;
import android.util.Log;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.loveto.common.JsonUtils;
import com.loveto.constant.LovetoConstant;

public class C2dmReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.e("C2DM", "onReceive");
		
		if(intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
			handleRegistration(context, intent);
		} else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
			handleMessage(context, intent);
		}
	}

	private void handleMessage(Context context, Intent intent) {
		Log.e("C2DM", "handleMessage");
		// 화면깨우기
		//PushWakeLock.acquireCpuWakeLock(context);
		
		//심플 토스트
		//Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
		
		//메시지 받고 제목과 본문으로 나누기
		String msg = intent.getStringExtra("msg");
		Log.d("C2DM", "msg: " + msg);
		String[] msgArray = msg.split("\\$\\@\\#\\%");
		String Title = msgArray[0];
		Log.d("C2DM", "Title: " + Title);
		String Body = msgArray[1];
		Log.d("C2DM", "Body: " + Body);
		
		//스테이터스바 알림 설정
		int icon = R.drawable.icon_loveto_mini; 
		CharSequence notiTicker = Title;
		CharSequence notiTitle = Title;
		CharSequence notiText = Body;
		long now = System.currentTimeMillis();
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(ns);
		Notification notification = new Notification(icon,notiTicker,now);
		
		//스테이터스바 알림 클릭 시 이동할 위치 지정
		Intent notificationIntent;
		if (Title.equals("러브토 쪽지 도착!")) {
			notificationIntent = new Intent(context,MessageMainActivity.class);
		} else {
			notificationIntent = new Intent(context,JoinedTournamentListActivity.class);
		}
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
		
		//스테이터스바 기타 속성 설정 및 화면 표시
		notification.setLatestEventInfo(context, notiTitle, notiText, contentIntent);
		notification.defaults |= Notification.DEFAULT_SOUND;
		notification.defaults |= Notification.DEFAULT_VIBRATE;
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		mNotificationManager.notify(1, notification);
		
		//if(km.inKeyguardRestrictedInputMode()){
		//화면 켜짐 상태 확인
		KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); //잠금 화면인지?
		PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); //화면이 켜졌는지?
		if (pm.isScreenOn() && !km.inKeyguardRestrictedInputMode()){
			//잠금 상태가 아닐 때 : 커스텀 토스트
			//토스트 레이아웃
			LinearLayout toastLayout = new LinearLayout(context);
			LinearLayout.LayoutParams toastLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			toastLayout.setLayoutParams(toastLayoutParams);
			toastLayout.setOrientation(LinearLayout.HORIZONTAL);
			toastLayout.setBackgroundResource(R.drawable.bg_push_toast);
			toastLayout.setPadding(10, 10, 10, 10);
			//아이콘
			LinearLayout.LayoutParams iconParams = new LayoutParams(58, 58);
			iconParams.gravity = Gravity.CENTER_VERTICAL;
			ImageView iconView = new ImageView(context);
			iconView.setImageResource(R.drawable.icon_loveto_push); 
			toastLayout.addView(iconView, iconParams); 
			//텍스트 표시 레이아웃
			LinearLayout textLayout = new LinearLayout(context);
			textLayout.setOrientation(LinearLayout.VERTICAL);
			LinearLayout.LayoutParams textLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			textLayoutParams.leftMargin = 10;
			//제목 표시
			TextView titleView = new TextView(context);
			LinearLayout.LayoutParams titleViewParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			titleView.setText(Title);
			titleView.setTextColor(Color.parseColor("#e4e542"));
			titleView.setTextSize(12);
			textLayout.addView(titleView, titleViewParams);
			//본문 표시
			TextView bodyView = new TextView(context);
			LinearLayout.LayoutParams bodyViewParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			bodyView.setText(Body);
			bodyView.setTextColor(Color.parseColor("#ffffff"));
			bodyView.setTextSize(12);
			bodyView.setMaxWidth(270);
			textLayout.addView(bodyView, bodyViewParams);
			//텍스트를 레이아웃에 넣기
			toastLayout.addView(textLayout,textLayoutParams);
			Toast toastView = new Toast(context);
			toastView.setView(toastLayout);
			toastView.setDuration(Toast.LENGTH_LONG);
			toastView.setGravity(Gravity.CENTER, 0, 0);
			toastView.show();
		} else {
			//잠금 상태 일 때 : 다이얼로그
			Intent intentDialog = new Intent (context,DialogForPush.class);
			intentDialog.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intentDialog.putExtra("Title", Title);
			intentDialog.putExtra("Body", Body);
			context.startActivity(intentDialog);
		}
		
	}

	private void handleRegistration(Context context, Intent intent) {
		Log.e("C2DM", "handleRegistration");
		  
		// 서버에서 넘어오는 메시지의 내용에 key 이름 "registration_id" 에는 이 기기에만 사용하는 인증키 값이 담겨서 넘어온다.
		String registration = intent.getStringExtra("registration_id");
		  
		if (intent.getStringExtra("error") != null)
		{
			Log.e("C2DM", "error");
		}
		else if (intent.getStringExtra("unregistered") != null)
		{
			Log.e("C2DM", "unregistered");
		}
		else if (registration != null)
		{
			Log.e("C2DM", registration);
			SharedPreferences pref = context.getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
			String memberid = pref.getString("memberid", "");
			
			// DB의 사용자 테이블에 저장.
			
			//서버에 정보 보내기
			try {
				Log.e("C2DM", "memberid : " + memberid);
				StringBuffer url = new StringBuffer(LovetoConstant.REGISTRATIONID_SAVE_URL);
				url.append("?memberid=").append(URLEncoder.encode(memberid, "UTF-8"));
				url.append("&registrationid=").append(URLEncoder.encode(registration, "UTF-8"));
				Log.d("tag", "url : " + url.toString());
				String jsonText = JsonUtils.getStringFromUrl(url.toString());
				Log.d("tag", "jsonText : " + jsonText);
				JSONObject object = new JSONObject(jsonText);
				String result = object.getString("result");
				String err = object.getString("err");
				if ("T".equals(result)) {
					Toast.makeText(context,  "푸쉬알람 기능을 사용합니다.", Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(context, err + " : 푸쉬알람 기능을 사용할 수 없습니다.", Toast.LENGTH_LONG).show();
				}
			} catch (Exception e) {
				Toast.makeText(context, "푸쉬알람 기능을 사용할 수 없습니다.", Toast.LENGTH_LONG).show();
			}
			
		}
	}

}
